package simple.cat.server;

import simple.cat.util.HttpProtocolUtil;
import simple.cat.util.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author zheng9feng
 * @Description 封装响应信息
 * 1.根据请求路径加载资源并写入输出流
 * @Date 2020/12/25 22:34
 */
public class Response {
	/**
	 * 资源绝对路径
	 * 根据请求url拼接得到
	 * ? 请求资源的路径放在响应对象里是不是不太合
	 */
	private String resourceAbsolutePath;
	private OutputStream outputStream;
	
	public Response() {
	}
	
	public Response(OutputStream outputStream) {
		this.outputStream = outputStream;
	}
	
	public String getResourceAbsolutePath() {
		return resourceAbsolutePath;
	}
	
	public void setResourceAbsolutePath(String resourceAbsolutePath) {
		this.resourceAbsolutePath = resourceAbsolutePath;
	}
	
	public OutputStream getOutputStream() {
		return outputStream;
	}
	
	public void setOutputStream(OutputStream outputStream) {
		this.outputStream = outputStream;
	}
	
	/**
	 * 获取资源绝对路径
	 *
	 * @param url
	 */
	public void buildResourceAbsolutePath(String url) {
		// 先获取当前文件所在根目录
		URL rootUrl = Response.class.getResource("/");
		String rootUrlPath = rootUrl.getPath().replaceAll("\\\\","");
		System.out.println("根目录:" + rootUrlPath);
		
		this.resourceAbsolutePath = rootUrlPath + url;
		System.out.println("resourceAbsolutePath:" + resourceAbsolutePath);
	}
	
	/**
	 * 输出响应内容
	 *
	 * @param content 响应内容
	 * @throws IOException
	 */
	public void output(String content) throws IOException {
		outputStream.write(content.getBytes(StandardCharsets.UTF_8));
	}
	
	/**
	 * 输出静态文件
	 *
	 * @throws Exception
	 */
	public void outputHtml() throws Exception {
		// 根据路径加载资源文件
		// /Users/zheng9feng/simple-framework-handwriting/simple-tomcat/target/classes/index.html
		File resourceFile = new File(resourceAbsolutePath);
		if (resourceFile.exists() && resourceFile.isFile()) {
			// 读取文件
			FileInputStream fileInputStream = new FileInputStream(resourceFile);
			StaticResourceUtil.outputStaticResource(fileInputStream, outputStream);
			
		} else {
			output(HttpProtocolUtil.getHttpHeader4NotFound());
		}
		// 写出文件
	}
}
